package com.x.controller;

import com.x.pojo.User;
import lombok.Data;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: UserController
 * Package: IntelliJ IDEA
 * Description:
 * Written by HanXu
 * Create 2024.09.13 9:48
 */

@Controller
@RequestMapping("Exception")
public class UserController {

    /**
     * @Validated 参数校验注解生效
     *      校验对于param和json都有效
     *      接收json时，加两个注解@Validated @RequestBody
     *
     * BindingResult类对象能收集到实体类错误的属性校验信息
     */
    @PostMapping("register")
    public Object register(@Validated @RequestBody User user, BindingResult result){

        if(result.hasErrors()){
            //如果有校验信息
            Map map = new HashMap<>();
            map.put("code",400);//给前端返回错误码400
            map.put("message","参数校验异常");
            System.out.println(map);
            return map;
        }

        System.out.println(user.toString());
        return user;
    }

    @GetMapping("data1")
    public String data1(){
        String name =null;
        name.toString();
        //空指针异常
        return "";
    }

    @GetMapping("data2")
    public String data2(){
        int i=1/0;
        //除以零异常
        return "";
    }
}
